﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using XNAQ3Lib;
using XNAQ3Lib.Q3BSP;
using Game.Particles;
using Game.Particles.ParticleSystems;

namespace Game
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;

        ParticleSystem explosionParticles;
        ParticleSystem explosionSmokeParticles;
        ParticleSystem projectileTrailParticles;
        ParticleSystem smokePlumeParticles;
        ParticleSystem fireParticles;

        SpriteBatch spriteBatch;
        Matrix view;
        Matrix projection;
        Vector3 cameraPosition;
        Vector3 cameraTarget;

        KeyboardState lastKeyboardState;
        MouseState lastMouseState;
        Q3BSPLevel level;

        float aspectRatio;
        float nearPlane;
        float farPlane;
        float fieldOfView;

        float leftrightRot = MathHelper.PiOver2;
        float updownRot = -MathHelper.Pi / 10.0f;
        const float rotationSpeed = 0.3f;
        const float moveSpeed = 80.0f;

        Vector3 gravity = new Vector3(0, -20, 0);
        Vector3 traceBoxMinNormal = new Vector3(-5, -15, -5);
        Vector3 traceBoxMaxNormal = new Vector3(5, 15, 5);

        Vector3 traceBoxClimbDifference = new Vector3(0, -2, 0);
        Vector3 traceBoxMinClimb = new Vector3(-5, -13, -5);
        Vector3 traceBoxMaxClimb = new Vector3(5, 15, 5);

        Boolean inAir = false;
        Int32 jumpCoefficent = 5;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);            
            Content.RootDirectory = "Content";

            // Construct our particle system components.
            explosionParticles = new ExplosionParticleSystem(this, Content);
            explosionSmokeParticles = new ExplosionSmokeParticleSystem(this, Content);
            projectileTrailParticles = new ProjectileTrailParticleSystem(this, Content);
            smokePlumeParticles = new SmokePlumeParticleSystem(this, Content);
            fireParticles = new FireParticleSystem(this, Content);

            // Set the draw order so the explosions and fire
            // will appear over the top of the smoke.
            smokePlumeParticles.DrawOrder = 100;
            explosionSmokeParticles.DrawOrder = 200;
            projectileTrailParticles.DrawOrder = 300;
            explosionParticles.DrawOrder = 400;
            fireParticles.DrawOrder = 500;

            // Register the particle system components.
            Components.Add(explosionParticles);
            Components.Add(explosionSmokeParticles);
            Components.Add(projectileTrailParticles);
            Components.Add(smokePlumeParticles);
            Components.Add(fireParticles);
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            Window.Title = "Crater v0.01";

            nearPlane = 1.0f;
            farPlane = 1000.0f;
            fieldOfView = 45.0f;
            aspectRatio = (float)graphics.GraphicsDevice.Viewport.Width / (float)graphics.GraphicsDevice.Viewport.Height;

            projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(fieldOfView), aspectRatio, nearPlane, farPlane);
            cameraPosition = new Vector3(40, 20, 0);
            cameraTarget = new Vector3(0, 20, 0);
            
            Mouse.SetPosition(graphics.GraphicsDevice.Viewport.Width / 2, graphics.GraphicsDevice.Viewport.Height / 2);
            lastMouseState = Mouse.GetState();

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            level = new Q3BSPLevel(Q3BSPRenderType.StaticBuffer);
            level.BasePath = "reqtourney1";
            if (level.LoadFromFile(level.BasePath + ".bsp"))
            {
                bool levelLoaded = level.InitializeLevel(GraphicsDevice, Content, @"shaders\");
            }

            // TODO: use this.Content to load your game content here
            lastMouseState = Mouse.GetState();
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            //updateMovements(gameTime);
            float timeDifference = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000.0f;
            
            Vector3 moveVector = ProcessInput(timeDifference);

            HandleGravity(gravity * timeDifference);
            AddToCameraPosition(moveVector * timeDifference);
            UpdateViewMatrix();

            const int fireParticlesPerFrame = 5;

            // Create a number of fire particles, randomly positioned around a circle.
            for (int i = 0; i < fireParticlesPerFrame; i++)
            {
                fireParticles.AddParticle(new Vector3(0, 0, 0), Vector3.Zero);
            }
            // Create one smoke particle per frmae, too.
            smokePlumeParticles.AddParticle(new Vector3(0, 0, 0), Vector3.Zero);

            base.Update(gameTime);
        }

        private Vector3 ProcessInput(float amount)
        {
            MouseState currentMouseState = Mouse.GetState();

            float xDifference = currentMouseState.X - lastMouseState.X;
            float yDifference = currentMouseState.Y - lastMouseState.Y;
            leftrightRot -= rotationSpeed * xDifference * amount;
            updownRot -= rotationSpeed * yDifference * amount;
            updownRot = MathHelper.Clamp(updownRot, MathHelper.ToRadians(-89.9f), MathHelper.ToRadians(89.9f));
            Mouse.SetPosition(graphics.GraphicsDevice.Viewport.Width / 2, graphics.GraphicsDevice.Viewport.Height / 2);

            Vector3 moveVector = Vector3.Zero;
            KeyboardState keyState = Keyboard.GetState();

            if (keyState.IsKeyDown(Keys.Escape))
                this.Exit();
            
            if (keyState.IsKeyDown(Keys.Up) || keyState.IsKeyDown(Keys.W))
                moveVector += Vector3.Forward;
            if (keyState.IsKeyDown(Keys.Down) || keyState.IsKeyDown(Keys.S))
                moveVector += Vector3.Backward;
            if (keyState.IsKeyDown(Keys.Right) || keyState.IsKeyDown(Keys.D))
                moveVector += Vector3.Right;
            if (keyState.IsKeyDown(Keys.Left) || keyState.IsKeyDown(Keys.A))
                moveVector += Vector3.Left;
            if ((keyState.IsKeyDown(Keys.Q) || keyState.IsKeyDown(Keys.Space)) && !inAir)
                moveVector += Vector3.Up * jumpCoefficent;
            if (keyState.IsKeyDown(Keys.Z))
                moveVector += Vector3.Down;

            return moveVector;
        }

        private void AddToCameraPosition(Vector3 vectorToAdd)
        {
            // Just allow movement on the plane
            Matrix movementRotation = Matrix.CreateRotationY(leftrightRot);
            Vector3 rotatedVector = Vector3.Transform(vectorToAdd, movementRotation);            
            cameraPosition += moveSpeed * rotatedVector;           

            Q3BSPCollisionData collisionDataNormal = level.TraceBox(cameraPosition, cameraPosition + rotatedVector,
                traceBoxMinNormal, traceBoxMaxNormal);

            Q3BSPCollisionData collisionDataClimb = level.TraceBox(cameraPosition, cameraPosition + rotatedVector,
                            traceBoxMinClimb, traceBoxMaxClimb);

            if (collisionDataNormal.inSolid)
            {
                if (collisionDataClimb.inSolid)
                {
                    Vector3 oppositeDirection = rotatedVector * -1;
                    cameraPosition += moveSpeed * oppositeDirection;
                }
                else
                {
                    Vector3 oppositeDirection = traceBoxClimbDifference * -1;
                    cameraPosition += oppositeDirection;
                }
            }
        }

        private void HandleGravity(Vector3 gravityInTime)
        {
            inAir = true;
            cameraPosition += gravityInTime;
            Q3BSPCollisionData collisionData = level.TraceBox(cameraPosition, cameraPosition + Vector3.Down,
                traceBoxMinNormal, traceBoxMaxNormal);
            if (collisionData.inSolid)
            {
                inAir = false;
                cameraPosition += gravityInTime * -1;                
            }
        }

        private void UpdateViewMatrix()
        {
            Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);

            Vector3 cameraRotatedTarget = Vector3.Transform(Vector3.Forward, cameraRotation);
            Vector3 cameraFinalTarget = cameraPosition + cameraRotatedTarget;

            view = Matrix.CreateLookAt(cameraPosition, cameraFinalTarget, Vector3.Up);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);            

            // Pass camera matrices through to the particle system components.
            explosionParticles.SetCamera(view, projection);
            explosionSmokeParticles.SetCamera(view, projection);
            projectileTrailParticles.SetCamera(view, projection);
            smokePlumeParticles.SetCamera(view, projection);
            fireParticles.SetCamera(view, projection);

            ResetRenderState();
            // TODO: Add your drawing code here
            level.RenderLevel(cameraPosition, view, projection, gameTime, GraphicsDevice);

            base.Draw(gameTime);
        }

        private void ResetRenderState()
        {
            GraphicsDevice.RenderState.AlphaBlendEnable = false;
            GraphicsDevice.RenderState.AlphaTestEnable = false;
            GraphicsDevice.RenderState.DepthBufferEnable = true;

            GraphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap;
            GraphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap;
        }
    }
}
